// 获取对象中长度最大的字符串
export const getLongistStr = (obj: { [key: string]: any }, str: string) => {
  let arr: any = [];
  const eachObject = (mObj: { [key: string]: any }) => {
    mObj.constructor == Object && Object.values(mObj)?.forEach((x: any) => {
      x?.[str] && arr.push(x?.[str]);
      x.constructor == Object && eachObject(x);
    })
  }
  eachObject(obj);
  return arr.find((x: any) => x.length === Math.max(...arr.map((y: any) => y.length)));
};

// 获取url地址中的query参数
export const getQuerys = (url: string) => {
  const index = url.indexOf('?');
  let obj: any = {};
  if (index !== -1) {
    const queryStrArr = url.substring(index + 1).split('&');
    for (let i = 0; i < queryStrArr.length; i++) {
      const itemArr = queryStrArr[i].split('=');
      obj[itemArr[0]] = itemArr[1];
    }
  }
  return obj;
}

// 将file文件上传转化为base64
export const getBase64ByFile = (file: Blob) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  })
}

// 图片url转化为base64
export const getBase64ByUrl = (url: string) => {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = image.width;
      canvas.height = image.height;
      ctx?.drawImage(image,0,0,image.width,image.height);
      const ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
      const dataUrl = canvas.toDataURL(`image/${ext}`);
      resolve(dataUrl || '');
    }
    image.src = url;
  })
}

// 判断变量是否为数组
export const isArray = (e: any) => {
  return Array.isArray(e);
}